const { logger } = require('ee-core/log')
const { ImapFlow } = require('imapflow');
const { simpleParser } = require('mailparser');
const { Notification } = require('electron')

class EmailService {
    constructor() {
        this.client = null;
        this.emailBoxList = [];
        this.refreshTime = 1000 * 60 * 5; // 5 分钟刷新一次
        this.timer = null;
        this.event = null
        this.accountList = [{
            name:'qq',
            email: '3317822213@qq.com',
            password: 'mqzqejgqmnldchbc',
            host: 'imap.qq.com'
        },{
            name:'163',
            email: 'lzh3317822213@163.com',
            password: 'GFhTdgRi2LQ4jYfH',
            host: 'imap.163.com'
        }]

        this.imapConfig = {
            host:'',
            port: 993,
            secure: true,
            auth: {
                user: '',
                pass: ''
            },
            logger: false
        };

        this.connect();
    }

    /**
     *
     * @param {PlatformName} 平台名称 qq | 163
     * */
    async connect(PlatformName='qq') {
        logger.info('[开始连接邮箱服务] 配置连接平台为'+PlatformName);
        let findPlatfrom = this.accountList.find(i => i.name == PlatformName)
        this.imapConfig.auth.user = findPlatfrom.email;
        this.imapConfig.auth.pass = findPlatfrom.password;
        this.imapConfig.host = findPlatfrom.host;
        this.client = new ImapFlow(this.imapConfig);

        return new Promise(async (resolve, reject) => {
            try {
                await this.client.connect();
                logger.info('[邮箱连接成功]');

                await this.client.mailboxOpen('INBOX');
                resolve(true)
                this.client.on('exists', async () => {
                    console.log('📥 新邮件到达');

                    const uid = this.client.mailbox.exists;
                    if (!uid) return;

                    const lock = await this.client.getMailboxLock('INBOX');
                    try {
                        const message = await this.client.fetchOne(uid, { source: true });
                        const parsed = await simpleParser(message.source);
                        const emailData = {
                            from: parsed.from?.text || '未知发件人',
                            to: parsed.to?.text || '未知收件人',
                            subject: parsed.subject || '无主题',
                            date: parsed.date || new Date(),
                            text: parsed.text || '',
                            html: parsed.html || '',
                            attachments: parsed.attachments || [],
                            uid: uid
                        };
                        console.log('📧 新邮件主题:', parsed.subject);
                        this.showNotification(emailData);
                        let channel = 'controller/emailService/newEmail';
                        this.event?.sender.send(channel, { type:'get:email:new', content: emailData, flag: channel });
                    } catch (err) {
                        console.error('❌ 获取或解析新邮件失败:', err);
                    } finally {
                        lock.release();
                    }
                });

                /* 添加断线重连机制 */
                this.client.on('error', (err) => {
                    console.error('连接邮箱出错: 稍后重试进行连接', err);
                    if (!this.client?.closed) {
                        this.client.logout().catch(() => {});
                    }
                    // 尝试重连
                    setTimeout(() => this.connect(), 5000); // 5秒后重连
                })

            } catch (err) {
                console.error('连接邮箱出错:', err);
                reject(false)
            }
        })
    }

    async getEmailListByAccount(page = 1, pageSize = 20) {
        console.log('分页获取列表 --- 第', page, '页', pageSize,'条');
        this.emailBoxList = [];

        // 1. 搜索所有邮件，确保是数字 UID
        const allUids = (await this.client.search({ all: true })).map(Number);
        const sortedUids = allUids.sort((a, b) => b - a); // UID 倒序

        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const pageUids = sortedUids.slice(startIndex, endIndex);

        if (pageUids.length === 0) {
            return { emailes: [], total: allUids.length };
        }

        for await (const msg of this.client.fetch(pageUids, {
            envelope: true,
            source: true,
            uid: true
        })) {
            const parsed = await simpleParser(msg.source);
            const emailData = {
                from: parsed.from?.text || '未知发件人',
                to: parsed.to?.text || '未知收件人',
                subject: parsed.subject || '无主题',
                date: parsed.date || new Date(),
                text: parsed.text || '',
                html: parsed.html || '',
                attachments: parsed.attachments || [],
                uid: msg.uid || '未知UID'
            };
            this.emailBoxList.push(emailData);
        }

        // 可选：按邮件时间再排一次
        this.emailBoxList.sort((a, b) => b.date - a.date);

        return { emailes: this.emailBoxList, total: allUids.length };
    }

    extractSenderName(from) {
        const match = from.match(/^"?([^"<@]+?)"?\s*<.*?>$/);
        if (match) return match[1].trim();
        const simpleEmailMatch = from.match(/^([^@]+)@/);
        return simpleEmailMatch ? simpleEmailMatch[1] : from;
    }

    showNotification(email) {
        new Notification({
            title: `📬 新邮件 -- 您有一封新的未处理邮件`,
            body: `\n发送人:${this.extractSenderName(email.from)}\n${email.subject}`,
        }).show();
    }

    /**
     * @name getEmailList
     * @description 获取邮件列表
     * @param {string} type
     * @param {string} content
     * @param {object} event
     * @param {number} page
     * @param {number} pageSize
     * @returns {Promise<{type: string, content: any, flag: string}>}
     * */
    async getEmailList(type, content, event, page = 1, pageSize = 20) {
        if (this.timer) clearInterval(this.timer);

        const emails = await this.getEmailListByAccount(page, pageSize);
        this.event = event;

        return {
            type,
            content: emails.emailes,
            flag: '/getEmailList',
            total: emails.total
        };
    }

    /**
     * @name switchUserAccount
     * @description 切换用户账号
     * @param {string} PlatformName  qq | 163
     *
     * */
    async switchUserAccount(PlatformName) {
        // 切换之前先断开之前的链接
        await this.client.logout().catch(() => {});
        // 重新进行配置链接
        await this.connect(PlatformName);
        let result = await this.getEmailListByAccount()
        return result
    }

    /**
     * @desc 创建写邮件的窗口
     * */
    createWriteEmailWin(){

    }
}

module.exports = {
    EmailService,
    emailService: new EmailService()
};